<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2021/1/4
 * Time: 10:34
 */
namespace App\Http\Middleware;

use App\Constant\ErrorConstant;
use App\MultiTrait\ResponseTrait;
use Illuminate\Auth\AuthenticationException;
use Laminas\Diactoros\ResponseFactory;
use Laminas\Diactoros\ServerRequestFactory;
use Laminas\Diactoros\StreamFactory;
use Laminas\Diactoros\UploadedFileFactory;
use Laravel\Passport\Http\Middleware\CheckClientCredentials;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;

class SystemCheckMiddleware extends CheckClientCredentials
{
    use ResponseTrait;

    /**
     * Handle an incoming request.
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @param mixed ...$scopes
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws AuthenticationException
     * @throws \Laravel\Passport\Exceptions\MissingScopeException
     */
    public function handle($request, \Closure $next, ...$scopes)
    {
        $psr = (new PsrHttpFactory(
            new ServerRequestFactory,
            new StreamFactory,
            new UploadedFileFactory,
            new ResponseFactory
        ))->createRequest($request);

        try {
            $psr = $this->server->validateAuthenticatedRequest($psr);
        } catch (OAuthServerException $e) {
            return $this->errorResponse(ErrorConstant::TOKEN_ERROR, $e->getMessage());
//            throw new AuthenticationException;
        }

        $this->validate($psr, $scopes);

        return $next($request);
    }
}

